<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>背景颜色更改器</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      html,
      body {
        height: 100%;
      }

      body {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .container {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .container h2 {
        background-color: #222;
        color: #fff;
        padding: 20px;
        border-radius: 4px;
        margin-bottom: 20px;
      }
      .container .color {
        color: #49a6e9;
      }

      .container .btn {
        text-transform: uppercase;
        background: transparent;
        color: #222;
        letter-spacing: 2px;
        font-weight: 700;
        transition: all 0.3s linear;
        border: 2px solid #222;
        cursor: pointer;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        font-size: 20px;
        padding: 8px 6px;
      }
      .container .btn:hover {
        color: #fff;
        background: #222;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h2>背景色：<span class="color">green</span></h2>
      <button class="btn">切换</button>
    </div>
    <script>
      const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
      const $btn = document.querySelector(".btn");
      const $color = document.querySelector(".color");

      function getRandomInt(min, max) {
        // [0, 1) * max - min + 1
        // [0, max - min + 1) + min
        // [min, max + 1) -> 向下取整
        // [min, max]
        return Math.floor(Math.random() * (max - min + 1) + min);
      }

      function getRandomColor(index) {
        let i = index;
        while (i === index) {
          i = getRandomInt(0, colors.length - 1);
        }
        return i;
      }

      let currentIndex = 0;

      function render() {
        document.body.style.backgroundColor = colors[currentIndex];
        $color.textContent = colors[currentIndex];
      }

      $btn.addEventListener("click", function (e) {
        currentIndex = getRandomColor(currentIndex);
        render();
      });
      render();
    </script>
  </body>
</html>
